﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ImageGrabberAPI
{
    class LinkFinder
    {
        /// <summary>
        /// Taken from http://stackoverflow.com/questions/122856/parse-html-links-using-c
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        public static List<Uri> FindUris(string message, string groupName)
        {
            string anchorPattern = "<a[\\s]+[^>]*?href[\\s]?=[\\s\\\"\']+(?<href>.*?)[\\\"\\']+.*?>(?<fileName>[^<]+|.*?)?<\\/a>";
            MatchCollection matches = Regex.Matches(message, anchorPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
            if (matches.Count > 0)
            {
                List<Uri> uris = new List<Uri>();

                foreach (Match m in matches)
                {
                    string url = m.Groups[groupName].Value;
                    Uri testUri = null;
                    if (Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out testUri))
                    {
                        uris.Add(testUri);
                    }
                }
                return uris;
            }
            return null;
        }

        /// <summary>
        /// Optimized version of FindUris by comparing them to mark
        /// </summary>
        /// <param name="message"></param>
        /// <param name="groupName"></param>
        /// <param name="mark"></param>
        /// <returns></returns>
        public static List<Uri> FindUrisByMark(string message, string groupName, string mark = "")
        {
            List<Uri> uris = FindUris(message, groupName);
            if (string.IsNullOrWhiteSpace(mark))
                return uris;
            List<Uri> newUriList = new List<Uri>();
            foreach (var uri in uris)
            {
                if (!uri.AbsoluteUri.Contains(mark))
                    continue;
                newUriList.Add(uri);
            }

            return newUriList;
        }
    }
}
